package com.bcx.wind.workflow.parser;

import org.apache.ibatis.io.Resources;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.xml.sax.EntityResolver;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

import java.io.IOException;
import java.io.InputStream;
import java.util.Locale;

import static com.bcx.wind.workflow.parser.ParserConstant.*;

/**
 * dtd resolver
 *
 * @author zhanglei
 */
public final class XmlResolver implements EntityResolver {

    private static final Logger LOGGER = LoggerFactory.getLogger(XmlResolver.class);


    @Override
    public InputSource resolveEntity(String publicId, String systemId) throws SAXException, IOException {
        try {
            if (systemId != null) {
                String lowerCaseSystemId = systemId.toLowerCase(Locale.ENGLISH);
                if (lowerCaseSystemId.contains(WORKFLOW_PROCESS_SYSTEM) ) {
                    return getInputSource(publicId, systemId);
                }
            }
            return null;
        } catch (Exception e) {
            if(LOGGER.isDebugEnabled()){
                LOGGER.debug(e.getMessage());
            }
            throw new SAXException(e.toString());
        }
    }

    private InputSource getInputSource(String publicId, String systemId) {
        InputSource source = null;

        try {
            InputStream in = Resources.getResourceAsStream(WORKFLOW_PROCESS_DTD);
            source = new InputSource(in);
            source.setPublicId(publicId);
            source.setSystemId(systemId);
        } catch (IOException e) {
            if(LOGGER.isDebugEnabled()){
                LOGGER.debug(e.getMessage());
            }
            // ignore, null is ok
        }
        return source;
    }
}
